//
//  HomeViewController.swift
//  XLWB
//
//  Created by 郭亮 on 16/3/11.
//  Copyright © 2016年 gl. All rights reserved.
//

import UIKit
import MJRefresh

private let cellId = "HomeCell"

//private enum LoadDatasType: String {
//   case LoadDatasTypeNew = "NEW"
//   case LoadDatasTypeMore = "MORE"
//}

class HomeViewController: BaseViewController {
    
    // MARK:-懒加载属性
    private lazy var titleBtn: SpringTitleButton = SpringTitleButton()
    private lazy var popoverAnimation: PopoverAnimation = PopoverAnimation()
    private lazy var statusViewModels: [StatusViewModel] = [StatusViewModel]()
    private lazy var cellHeightdict: [String: CGFloat] = [String: CGFloat]()
    private lazy var tipLable: UILabel = UILabel()

    // MARK:-系统回调方法
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !isLogin {
            visitorView.addRotationAimation()
            return
        }
        
        setupNavigationBar()
        
        //创建提示条
        setupTipLable()
        
        //创建头部视图
        setupHeaderFooterView()
        
        //接收通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "showPhotoBrowser:", name: showPhotoBrowserVcNote, object: nil)
    }
    
    deinit {
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

// MARK:-处理UI
extension HomeViewController {
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: "leftBarButtonItemClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "rightBarButtonItemClick")
        //添加中间视图
        titleBtn.setTitle("taylor", forState: .Normal)
        titleBtn.addTarget(self, action: "titleBtnClick:", forControlEvents: .TouchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    private func setupHeaderFooterView() {
        //头部视图
        let headerView = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "loadNewDatas")
        headerView.setTitle("下拉刷新数据", forState: .Idle)
        headerView.setTitle("松开刷新数据", forState: .Pulling)
        headerView.setTitle("正在刷新数据", forState: .Refreshing)
        tableView.mj_header = headerView
        headerView.beginRefreshing()
        
        //尾部视图
        let footerView = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: "loadMoreDatas")
        tableView.mj_footer = footerView
    }
    
    private func setupTipLable() {
        // 添加到导航栏
        navigationController?.navigationBar.insertSubview(tipLable, atIndex: 0)
        //设置frame
        tipLable.frame = CGRectMake(0, 14, UIScreen.mainScreen().bounds.width, 30)
        //设置属性
        tipLable.textColor = UIColor.redColor()
        tipLable.font = UIFont.systemFontOfSize(14)
        tipLable.textAlignment = .Center
        tipLable.hidden = true
        tipLable.backgroundColor = UIColor.orangeColor()
    }
    
    private func showTipLable(statusCount: Int) {
        tipLable.hidden = false
        tipLable.text = statusCount == 0 ? "没有发现新微博" : "发现\(statusCount)条微博"
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            self.tipLable.frame.origin.y = 44
            }) { (_) -> Void in
                UIView.animateWithDuration(1.0, delay: 1.0, options: [], animations: { () -> Void in
                  self.tipLable.frame.origin.y = 14
                    }, completion: { (_) -> Void in
                        self.tipLable.hidden = true
                })
        }
    }
}

// MARK:-事件点击
extension HomeViewController {
    @objc private func leftBarButtonItemClick() {
    print("leftBarButtonItemClick")
    }
    
    @objc private func rightBarButtonItemClick() {
    print("rightBarButtonItemClick")
    }
    
    @objc private func titleBtnClick(titleButton: SpringTitleButton) {
        //创建弹出控制器
        let popoverVc = PopoverViewController()
        //设置转场代理
        popoverAnimation.presentedFrame = CGRect(x: 150, y: 60, width: 150, height: 250)
        popoverAnimation.animationBlock = {[weak self](isPresented: Bool) -> Void in
        self?.titleBtn.selected = isPresented
        }
        popoverVc.transitioningDelegate = popoverAnimation
        //弹出view以后,后面的view不会被系统隐藏掉
        popoverVc.modalPresentationStyle = .Custom
        //modal控制器
        presentViewController(popoverVc, animated: true, completion: nil)
    }
    
    @objc private func showPhotoBrowser(note: NSNotification) {
        //拿出通知的信息
        guard let index = note.userInfo![showPhotoBrowserVcNoteIndex] as? NSIndexPath, pictureUrls = note.userInfo![showPhotoBrowserVcNoteUrls] as? [NSURL] else {
        return
        }
        //创建弹出控制器
        let browserVc = PhotoBrowserController(index: index, pictureUrls: pictureUrls)
        //弹出控制器
        presentViewController(browserVc, animated: true, completion: nil)
    }
}

// MARK:-请求页面数据
extension HomeViewController {
    @objc private func loadNewDatas() {
        loadDatas(true)
    }
    @objc private func loadMoreDatas() {
        loadDatas(false)
    }
    
    private func loadDatas(isNewDatas: Bool) {
        //创建url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //创建参数
        var parameters = [String: AnyObject]()
        guard let accessToken = UserAccountViewModal.shareInstance.accessToken?.access_token else {
            return
        }
        var since_id: Int = 0
        var max_id: Int = 0
        if isNewDatas == true {
            since_id = statusViewModels.first?.status?.id ?? 0
            parameters = ["access_token": accessToken, "since_id": since_id]
        }else {
            max_id = (statusViewModels.last?.status?.id ?? 1) - 1
            parameters = ["access_token": accessToken, "max_id": max_id]
        }
        
        //发请求
        NetworkingTolls.shareInstance.request(.RequestStyleGet, urlString: urlString, parameters: parameters) { (result, error) -> () in
            //字典转模型
            if result != nil {
                var newStatusViewModels = [StatusViewModel]()
                let dict = result as! [String: AnyObject]
                let resultArray = dict["statuses"] as! [[String: AnyObject]]
                for resultDict in resultArray {
                    //转模型
                    let status = Status(dict: resultDict)
                    //转VM
                    let statusVm = StatusViewModel(status: status)
                    //放入新数组
                    newStatusViewModels.append(statusVm)
                }
                if isNewDatas == true {
                    //拼接数组
                    self.statusViewModels = newStatusViewModels + self.statusViewModels
                    //刷新列表
                    self.tableView.reloadData()
                    //停止头部刷新
                    self.tableView.mj_header.endRefreshing()
                }else {
                    //拼接数组
                    self.statusViewModels = self.statusViewModels + newStatusViewModels
                    //刷新列表
                    self.tableView.reloadData()
                    //停止尾部刷新
                    self.tableView.mj_footer.endRefreshing()
                }
                //显示提示条
                self.showTipLable(newStatusViewModels.count)
            }
        }
    }
}

// MARK:-数据源方法
extension HomeViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusViewModels.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! HomeViewCell
        
        cell.statusVm = statusViewModels[indexPath.row]
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //拿出模型
        let statusVm = statusViewModels[indexPath.row]
        //判断缓存有没有高度
        if let cellHeight = cellHeightdict["\(statusVm.status?.id)"] {
        return cellHeight
        }else {
            // 计算cell的高度
            let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! HomeViewCell
            let cellHeight = cell.cellHeight(statusVm)
            //保存到缓存
            cellHeightdict["\(statusVm.status?.id)"] = cellHeight
            return cellHeight
        }
    }
}





